/**
 * 页面（页面肩部）级别按钮click事件
 */
import {print,ajax,base,promptBox,getMultiLang,pageTo} from 'nc-lightapp-front';
import requestApi, { isUploadedAttachments } from '../requestApi';
import {dataHandle,routeChange} from '../initTemplate';
import {imageScan, imageView} from "sscrp/rppub/components/image";
import linkVoucherApi from '../../../../public/components/linkvoucher/linkvoucher'
import linkBudgetApi from '../../../../public/components/linkbudget/linkbudget'
import linkQueryApi from '../../../../public/components/linkquery/linkquerybills';
import {updataFormData, updatacardTableData} from 'ssccommon/utils/changePageData';
import {removeDisplayScale}  from "ssccommon/utils/dataFilter";
import {toast } from 'nc-lightapp-front';
import { viewModel } from 'nc-lightapp-front';
let {  getGlobalStorage } = viewModel;
import { updateBodyData, delete3status } from '../utils'

const presetVar = window.presetVar
const pageButton = window.presetVar.pageButton;
const statusVar = window.presetVar.status;
const head1 = window.presetVar.head.head1;
const body1 = window.presetVar.body.body1;
const pageId = window.presetVar.pageId;
const { NCMessage } = base;
window.ntbCheck = 'false';
function pageButtonClick() {
    const bodys = window.presetVar.bodys;

    return {
        [pageButton.pageSave]: async () => {
            let props = this.props;
            let checkResult = props.form.isCheckNow('head') && props.cardTable.checkTableRequired();
            if (checkResult) {
                //校验附件是否必须上传
                const is_uploaded = await isUploadedAttachments.call(this, props)
                if(!is_uploaded) return

                let allData =  removeDisplayScale(props.createExtCardData(props.meta.getMeta().code, "head", bodys)) //props.createMasterChildData(pageId, head1, body1);
                let filterEmptyData = filterEmptyRows(allData);
                delete3status(filterEmptyData)
                let multiLang = this.props.MutiInit.getIntl(2011); //this.moduleId
                //清除复制行主键，暂时先这样处理,目前平台api没有支持
                for(var i=0;i<allData.bodys.mtapp_detail.rows.length;i++){
                    if(allData.bodys.mtapp_detail.rows[i]!=undefined&&allData.bodys.mtapp_detail.rows[i].status==2){
                        allData.bodys.mtapp_detail.rows[i].values.pk_mtapp_detail={};
                    }
                }

                if(!window.presetVar.noamount) {
                    let vat_amount = props.form.getFormItemsValue('head',"orig_amount").value;
                    if(vat_amount==undefined||vat_amount==null||vat_amount==0||vat_amount=='0.00000000'){
                        toast({content:multiLang && multiLang.get('201102FYYT-0019')/*"金额不能为空!"*/,color:'warning'});
                        return;
                    }
                }

                let billdataForFormula = props.createExtCardData(props.meta.getMeta().code, "head", bodys) //props.createMasterChildData(window.presetVar.pageCode, head1, body1);
                props.validateToSave( billdataForFormula , () => {
                // TOP NCCLOUD-91597 校验报销标准取模板时需要使用模板ID chengwbc ADD
	            filterEmptyData.templateid = props.meta.getMeta().pageid;
	            // BTM NCCLOUD-91597 校验报销标准取模板时需要使用模板ID
                requestApi.save({
                    status: props.getUrlParam('status'),
                    accessorybillid : this.accessorybillid || window.change_accessorybillid,
                    data: filterEmptyData,
                    success: (data) => {
                        if(data.data.userjson && JSON.parse(data.data.userjson) && JSON.parse(data.data.userjson).reimmsg && JSON.parse(data.data.userjson).reimmsg.length>0)
                        {
                            promptBox({
                                color: 'warning',       // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
                                title: multiLang && multiLang.get('201102JCLF_C-0002'),
                                content:JSON.parse(data.data.userjson).reimmsg,
                                noFooter: false,  // 是否显示底部按钮(确定、取消),默认显示(false),非必输
                                noCancelBtn: false,    // 是否显示取消按钮,，默认显示(false),非必输
                                beSureBtnName:multiLang && multiLang.get('2011-0003'),
                                cancelBtnName: multiLang && multiLang.get('2011-0002') ,
                                closeByClickBackDrop:false,
                                beSureBtnClick: ()=>{
                                      //设置表头数据
                                        props.form.setFormStatus(head1, statusVar.browse);
                                        bodys.forEach(bodyCode => {
                                            props.cardTable.setStatus(bodyCode, statusVar.browse);
                                        });

                                        updataFormData(props, head1, data.data.head[head1]);

                                        data.data.bodys && updateBodyData(props, data.data.bodys)

                                        pageTo.specialLinkTo('/erm/erbudgetmg/erbudgetmg/card/index.html',{scene:props.getUrlParam('scene'),status:statusVar.browse,id:props.form.getFormItemsValue(head1, 'pk_mtapp_bill').value,ts:new Date().getTime()});
                                        routeChange.call(this, this.props)
                                    },   // 确定按钮点击调用函数,非必输
                                cancelBtnClick: ()=>{
                                    updataFormData(props, head1, data.data.head[head1]);
                                    data.data.bodys && updateBodyData(props, data.data.bodys)
                                    pageTo.specialLinkTo('/erm/erbudgetmg/erbudgetmg/card/index.html',{scene:props.getUrlParam('scene'),status:statusVar.edit,id:props.form.getFormItemsValue(head1, 'pk_mtapp_bill').value,ts:new Date().getTime()});
                                    routeChange.call(this, this.props)
                                }  // 取消按钮点击调用函数,非必输
                            })
                        }else{
                            if(data.data.userjson && JSON.parse(data.data.userjson) && JSON.parse(data.data.userjson).bugetAlarm && JSON.parse(data.data.userjson).bugetAlarm.length>0){
                                promptBox({
                                    color: 'warning',       // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
                                    title: multiLang && multiLang.get('201102JCLF_C-0002'),//"提示信息"
                                    content:  (multiLang && multiLang.get('201102JCLF_C-0003'))+ JSON.parse(data.data.userjson).bugetAlarm+ (multiLang && multiLang.get('201102JCLF_C-0004')),
                                    noFooter: false,  // 是否显示底部按钮(确定、取消),默认显示(false),非必输
                                    noCancelBtn: false,    // 是否显示取消按钮,，默认显示(false),非必输
                                    beSureBtnName:  multiLang && multiLang.get('2011-0003'),
                                    cancelBtnName: multiLang && multiLang.get('2011-0002') ,
                                    beSureBtnClick: ()=>{
                                        window.ntbCheck = 'true';
                                        pageButtonClick.call(this)['pageSave']();
                                    }
                                })
                                return;
                            }else{
                                  //设置表头数据
                                    props.form.setFormStatus(head1, statusVar.browse);
                                    bodys.forEach(bodyCode => {
                                        props.cardTable.setStatus(bodyCode, statusVar.browse);
                                    });

                                    updataFormData(props, head1, data.data.head[head1]);
                                    data.data.bodys && updateBodyData(props, data.data.bodys)

                                    pageTo.specialLinkTo('/erm/erbudgetmg/erbudgetmg/card/index.html',{scene:props.getUrlParam('scene'),status:statusVar.browse,id:props.form.getFormItemsValue(head1, 'pk_mtapp_bill').value,ts:new Date().getTime()});
                                    routeChange.call(this, this.props)
                                }
                        }


                        props.button.setButtonsVisible({
                            [pageButton.pageSave]: false,
                            [pageButton.pageEdit]: true
                        });
                    }
                });

            } , body1 , null )
         }
        },
        [pageButton.pageEdit]: () => {
            let props = this.props;

            let multiLang = this.props.MutiInit.getIntl(2011);
            let scene = props.getUrlParam('scene');
            //获取单据编号
            let djbh = props.form.getFormItemsValue("head",['billno'])[0].value;
            let canEdit = true;
            let isMaker = true;
            //来源于审批中心
            if(scene == 'approve'  || scene == 'approvesce' ){
                isMaker = false;
                //判断单据是否是当前用户待审批
                ajax({
                    url: '/nccloud/riart/message/list.do',
                    async: false,
                    data: {
                        billno: djbh,
                        isread:'N'
                    },
                    success: result => {
                        if(result.data) {
                            if(result.data.total < 1){
                                toast({content:multiLang&&multiLang.get('201102SQFY-0027')/**"当前单据已审批，不可进行修改操作!"**/,color:'warning'});
                                canEdit =false;
                            }
                        }
                    }
                });
            }
            //来源于我的作业
            if(scene == 'zycl'){
                isMaker = false;
                //判断单据是否是当前用户待处理
                ajax({
                    url: '/nccloud/ssctp/sscbd/SSCTaskHandlePendingNumAction.do',
                    async: false,
                    data: {
                        billno: djbh
                    },
                    success: result => {
                        if(result.data) {
                            if(result.data.total < 1){
                                toast({content:multiLang&&multiLang.get('201102SQFY-0028')/*"当前单据已处理，不可进行修改操作!"*/,color:'warning'});
                                canEdit =false;
                            }
                        }
                    }
                });
            }

            //特殊数据权限校验
            ajax({
                url: '/nccloud/erm/pub/ErmBillEditAction.do',
                async: false,
                data: {
                    'pk_org': props.form.getFormItemsValue("head",['pk_org'])[0].value,
                    'billid': props.form.getFormItemsValue("head",['pk_mtapp_bill'])[0].value,
                    'billType':props.form.getFormItemsValue("head",['pk_tradetype'])[0].value
                },
                success: result => {

                },
                error: (data) => {
                    canEdit = false;
                    toast({ content: data.message, color: 'danger' });
                }
            });

            if(!canEdit){
                return;
            }

            if(isMaker){
                //驳回不重走流程单据，设置不可编辑字段
                requestApi.getUnEditAttributes({
                    data: {
                        'pk_org': props.form.getFormItemsValue("head",['pk_org'])[0].value,
                        'billid': props.form.getFormItemsValue("head",['pk_mtapp_bill'])[0].value,
                        'billType':props.form.getFormItemsValue("head",['pk_tradetype'])[0].value
                    },
                    success: (data) => {
                        if(!(data==undefined || data.length == 0)){
                            let formobj = {};
                            let mtapp_detailobj = [];

                            data.forEach((item) => {
                                if(item.indexOf('mtapp_detail.')>-1){
                                    mtapp_detailobj.push(item.split('.')[1]);
                                }else{
                                    formobj[item] = true;
                                }
                            })
                            props.form.setFormItemsDisabled('head',formobj)
                            props.cardTable.setColEditableByKey('mtapp_detail',mtapp_detailobj)
                        }
                    }
                })
            } else {
                //除制单人环节外的可编辑属性
                requestApi.getUnEditAttributes({
                    data: {
                        'pk_org': props.form.getFormItemsValue("head",['pk_org'])[0].value,
                        'billid': props.form.getFormItemsValue("head",['pk_mtapp_bill'])[0].value,
                        'billType':props.form.getFormItemsValue("head",['pk_tradetype'])[0].value
                    },
                    success: (data) => {
                        if(!(data==undefined || data.length == 0)){
                            let formobj = {};
                            let mtapp_detailobj = [];

                            data.forEach((item) => {
                                if(item.indexOf('mtapp_detail.')>-1){
                                    mtapp_detailobj.push(item.split('.')[1]);
                                }else{
                                    formobj[item] = false;
                                }
                            })
                            props.form.setFormItemsDisabled('head',formobj)
                            props.cardTable.setColEditableByKey('mtapp_detail',mtapp_detailobj,false)
                        }
                    }
                })
            }

            pageTo.specialLinkTo('/erm/erbudgetmg/erbudgetmg/card/index.html',{scene:props.getUrlParam('scene'),status:statusVar.edit,id:props.getUrlParam('id'),ts:new Date().getTime()});
            routeChange.call(this, this.props)
            let sceneout = this.props.getUrlParam('scene');
            if(sceneout == 'approve'  || sceneout == 'approvesce'  || sceneout == 'zycl') {
                props.button.setButtonsVisible({
                    [pageButton.pageSave]: true,
                    [pageButton.billSaveSubmit]: false,
                    [pageButton.pageEdit]: false,
                    ['mtapp_detail_Add']: true

                });
            }else{
                props.button.setButtonsVisible({
                    [pageButton.pageSave]: true,
                    [pageButton.pageEdit]: false,
                    ['mtapp_detail_Add']: true
                });
            }

        },
        [pageButton.pageCopy]: () => {
            let props = this.props;
            pageTo.specialLinkTo('/erm/erbudgetmg/erbudgetmg/card/index.html',{scene:props.getUrlParam('scene'),status:statusVar.add,copyFromBillId:props.getUrlParam('id'),ts:new Date().getTime()});
            routeChange.call(this, this.props)
            props.button.setButtonsVisible({
                ['mtapp_detail_Add']: true
            });
            window.assingUsers=[];
             //复制出来的单据要先清空附件产生的单据pk
             this.accessorybillid = '';
             this.setState({ billId: ''});
             let multiLang = this.props.MutiInit.getIntl(2011); //this.moduleId
             this.props.button.setButtonTitle('fileManager', multiLang&&multiLang.get('201102SQFY-0031')/**'附件'**/ + ' ' + 0 + ' ');
        },
        [pageButton.pageChange]: () => {
            let props = this.props;
            pageTo.specialLinkTo('/erm/erbudgetmg/erbudgetmg/card/index.html',{scene:props.getUrlParam('scene'),status:statusVar.add, changeFromBillId:props.getUrlParam('id'),ts:new Date().getTime()});
            routeChange.call(this, this.props)
            props.button.setButtonsVisible({
                ['mtapp_detail_Add']: true
            });
            window.assingUsers=[];
             //复制出来的单据要先清空附件产生的单据pk
             this.accessorybillid = '';
             this.setState({ billId: ''});
             let multiLang = this.props.MutiInit.getIntl(2011); //this.moduleId
             this.props.button.setButtonTitle('fileManager', multiLang&&multiLang.get('201102SQFY-0031')/**'附件'**/ + ' ' + 0 + ' ');
        },
        [pageButton.pageDel]: () => {//删除单据
            let props = this.props;
            props.form.setFormStatus(head1, statusVar.browse);
            props.cardTable.setStatus(body1, statusVar.browse);
            let allData =  props.createExtCardData(props.meta.getMeta().code, "head", bodys)
            requestApi.billRemove({
                data: allData,
                success: (data) => {
                    if (data.success) {
                        window.onbeforeunload=null;
                        window.top.close();
                    }
                }
            });
        },
        [pageButton.billInvalid]: () => {//单据作废
            let props = this.props;
            props.form.setFormStatus(head1, statusVar.browse);
            props.cardTable.setStatus(body1, statusVar.browse);
            let allData = props.createExtCardData(props.meta.getMeta().code, "head", bodys);
            requestApi.billInvalid({
                data: allData,
                success: (data) => {
                    //设置表头数据
                    // TOP 性能优化，变更页面数据更新方法 chengwbc MOD
                    // props.form.setAllFormValue({[head1]: data.data.head[head1]})
                    updataFormData(props, head1, data.data.head[head1]);
                    // BTM 性能优化，变更页面数据更新方法
                    //设置表体数据
                    // TOP 性能优化，变更页面数据更新方法 chengwbc MOD
                    // data.data.body && props.cardTable.setTableData(body1, data.data.body[body1]);
                    data.data.bodys && updateBodyData(props, data.data.bodys)
                    // BTM 性能优化，变更页面数据更新方法

                    pageTo.specialLinkTo('/erm/erbudgetmg/erbudgetmg/card/index.html',{scene:props.getUrlParam('scene'),status:statusVar.browse,id:props.getUrlParam('id'),ts:new Date().getTime()});
                    routeChange.call(this, this.props)
                }
            });
        },
        [pageButton.billEnable]: () => { //单据重启
            let props = this.props;
            props.form.setFormStatus(head1, statusVar.browse);
            props.cardTable.setStatus(body1, statusVar.browse);
            let allData = props.createExtCardData(props.meta.getMeta().code, "head", bodys);
            requestApi.billEnable({
                data: allData,
                success: (data) => {
                    //设置表头数据
                    // TOP 性能优化，变更页面数据更新方法 chengwbc MOD
                    // props.form.setAllFormValue({[head1]: data.data.head[head1]})
                    updataFormData(props, head1, data.data.head[head1]);
                    // BTM 性能优化，变更页面数据更新方法
                    //设置表体数据
                    // TOP 性能优化，变更页面数据更新方法 chengwbc MOD
                    // data.data.body && props.cardTable.setTableData(body1, data.data.body[body1]);
                    data.data.body && updatacardTableData(props, body1, data.data.body[body1]);
                    // BTM 性能优化，变更页面数据更新方法
                    pageTo.specialLinkTo('/erm/erbudgetmg/erbudgetmg/card/index.html',{scene:props.getUrlParam('scene'),status:statusVar.browse,id:props.getUrlParam('id'),ts:new Date().getTime()});
                    routeChange.call(this, this.props)
                }
            });
        },
        [pageButton.billClose]: () => {//单据关闭
            let props = this.props;
            props.form.setFormStatus(head1, statusVar.browse);
            props.cardTable.setStatus(body1, statusVar.browse);
            let allData = props.createExtCardData(props.meta.getMeta().code, "head", bodys);
            requestApi.billClose({
                data: allData,
                success: (data) => {
                    //设置表头数据
                    // TOP 性能优化，变更页面数据更新方法 chengwbc MOD
                    // props.form.setAllFormValue({[head1]: data.data.head[head1]})
                    updataFormData(props, head1, data.data.head[head1]);
                    // BTM 性能优化，变更页面数据更新方法
                    //设置表体数据
                    // TOP 性能优化，变更页面数据更新方法 chengwbc MOD
                    // data.data.body && props.cardTable.setTableData(body1, data.data.body[body1]);
                    data.data.body && updatacardTableData(props, body1, data.data.body[body1]);
                    // BTM 性能优化，变更页面数据更新方法

                    pageTo.specialLinkTo('/erm/erbudgetmg/erbudgetmg/card/index.html',{scene:props.getUrlParam('scene'),status:statusVar.browse,id:props.getUrlParam('id'),ts:new Date().getTime()});
                    routeChange.call(this, this.props)
                }
            });
        },
        [pageButton.pagePrint]: () => { //打印单据

            let vdata = {};
            vdata.billId = this.props.getUrlParam('id');
            vdata.billType = window.presetVar.billtype;
            ajax({
                url: '/nccloud/erm/erbudgetmg/FysqPrintValidaAction.do',
                data: vdata,
                success: (data) => {
                    if (!data.data.canPrint){
                        NCMessage.create({content:data.data.errMesg, color: 'error', position: 'bottom'});
                    }else {
                        print(
                            'pdf',  //支持两类: 'html'为模板打印, 'pdf'为pdf打印
                            '/nccloud/erm/pub/ErmPrintBillAction.do', //后台服务url
                            {
                               billtype:window.presetVar.billtype,  //单据类型
                               funcode:(this.props.getUrlParam("appcode")==undefined||this.props.getUrlParam("appcode")=='')?this.props.getSearchParam("c"):this.props.getUrlParam("appcode"),         //功能节点编码，即模板编码
                               nodekey:'2611_IWEB',     //模板节点标识
                               oids:[this.props.getUrlParam('id')],    // 功能节点的数据主键
                            }
                          )
                    }
                }
            })


        },
        [pageButton.imageUpload]: () => {//影像扫描
            let props = this.props;

            let billdata =  props.createExtCardData(props.meta.getMeta().code, "head", bodys);
            let openbillid = billdata.head.head.rows[0].values.pk_mtapp_bill.value || props.getUrlParam('id') || this.state.billId || "";

            var billInfoMap = {};

            //基础字段 单据pk,单据类型，交易类型，单据的组织
            billInfoMap.pk_billid = openbillid;
            billInfoMap.pk_billtype = billdata.head.head.rows[0].values.pk_billtype.value;
            billInfoMap.pk_tradetype = billdata.head.head.rows[0].values.pk_tradetype.value;
            billInfoMap.pk_org = billdata.head.head.rows[0].values.pk_org.value;

            //影像所需 FieldMap
            billInfoMap.BillType = billdata.head.head.rows[0].values.pk_tradetype.value;
            billInfoMap.BillDate = billdata.head.head.rows[0].values.creationtime.value;
            billInfoMap.Busi_Serial_No = billdata.head.head.rows[0].values.pk_mtapp_bill.value;
            billInfoMap.pk_billtype = billdata.head.head.rows[0].values.pk_billtype.value;
            billInfoMap.OrgNo = billdata.head.head.rows[0].values.pk_org.value;
            billInfoMap.BillCode = billdata.head.head.rows[0].values.billno.value;
            billInfoMap.OrgName = billdata.head.head.rows[0].values.pk_org.display;
            billInfoMap.Cash = billdata.head.head.rows[0].values.orig_amount.value;

            console.log("billInfoMap"+JSON.stringify(billInfoMap));
            imageScan(billInfoMap, 'iweb');
        }
        ,
        [pageButton.imageShow]: () => {//影像查看
            let props = this.props;
            let billdata =  props.createExtCardData(props.meta.getMeta().code, "head", bodys);
            let openbillid = billdata.head.head.rows[0].values.pk_mtapp_bill.value || props.getUrlParam('id') || this.state.billId || "";

            var billInfoMap = {};

            //基础字段 单据pk,单据类型，交易类型，单据的组织
            billInfoMap.pk_billid = openbillid;
            billInfoMap.pk_billtype = billdata.head.head.rows[0].values.pk_billtype.value;
            billInfoMap.pk_tradetype = billdata.head.head.rows[0].values.pk_tradetype.value;
            billInfoMap.pk_org = billdata.head.head.rows[0].values.pk_org.value;
            imageView(billInfoMap,  'iweb');
        }
        ,
        [pageButton.billSubmit]: async () => {//提交
            let props = this.props;
            let allData = props.createExtCardData(props.meta.getMeta().code, "head", bodys);
            //提交校验附件是否必须上传
            const is_uploaded = await isUploadedAttachments.call(this, props)
            if(!is_uploaded) return
            allData.userjson = window.ntbCheck;
            //清除复制行主键，暂时先这样处理,目前平台api没有支持
            for(var i=0;i<allData.bodys.mtapp_detail.rows.length;i++){
                if(allData.bodys.mtapp_detail.rows[i]!=undefined&&allData.bodys.mtapp_detail.rows[i].status==2){
                    allData.bodys.mtapp_detail.rows[i].values.pk_mtapp_detail={};
                }
            }
            delete3status(allData)
            // TOP NCCLOUD-91597 校验报销标准取模板时需要使用模板ID chengwbc ADD
            allData.templetid = props.meta.getMeta().pageid;
            // BTM NCCLOUD-91597 校验报销标准取模板时需要使用模板ID
            requestApi.billSubmit({
                accessorybillid : this.accessorybillid || window.change_accessorybillid,
                data: allData,
                status: props.getUrlParam('status'),
                success: (data) => {
		            //设置了指派
                    let multiLang = this.props.MutiInit.getIntl(2011); //this.moduleId
                    if(data.data.workflow && (data.data.workflow == 'approveflow'|| data.data.workflow == 'workflow')){
                        this.setState({
                            compositedata:data.data,
                            compositedisplay:true
                        }) ;
                    } else{
                        this.setState({
                            compositedisplay:false
                        }) ;
                        if(data.data.userjson && JSON.parse(data.data.userjson) && JSON.parse(data.data.userjson).bugetAlarm && JSON.parse(data.data.userjson).bugetAlarm.length>0){
                            promptBox({
                                color: 'warning',       // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
                                title: multiLang && multiLang.get('201102JCLF_C-0002'),//"提示信息"
                                content:  (multiLang && multiLang.get('201102JCLF_C-0003'))+ JSON.parse(data.data.userjson).bugetAlarm + (multiLang && multiLang.get('201102JCLF_C-0004')),
                                noFooter: false,  // 是否显示底部按钮(确定、取消),默认显示(false),非必输
                                noCancelBtn: false,    // 是否显示取消按钮,，默认显示(false),非必输
                                beSureBtnName:  multiLang && multiLang.get('2011-0003'),
                                cancelBtnName: multiLang && multiLang.get('2011-0002') ,
                                beSureBtnClick: ()=>{
                                    window.ntbCheck = 'true';
                                    pageButtonClick.call(this)['billSubmit']();
                                },
                                cancelBtnClick: () => {
                                    pageTo.specialLinkTo('/erm/erbudgetmg/erbudgetmg/card/index.html',{scene:props.getUrlParam('scene'),status:statusVar.browse,id:props.form.getFormItemsValue(head1, 'pk_mtapp_bill').value,ts:new Date().getTime()});
                                    routeChange.call(this, this.props)
                                    window.assingUsers = [];    //清空指派人信息
                                }
                                //cancelBtnClick: functionCancel  // 取消按钮点击调用函数,非必输
                            })
                        } else {
                            //处理按钮状态
                            dataHandle.call(this, data.data.head[head1], props);

                            updatePageDataAfter(props, data.data.head[head1], data.data.bodys)

                            pageTo.specialLinkTo('/erm/erbudgetmg/erbudgetmg/card/index.html',{scene:props.getUrlParam('scene'),status:statusVar.browse,id:props.form.getFormItemsValue(head1, 'pk_mtapp_bill').value});
                            routeChange.call(this, this.props)
                            window.assingUsers = [];    //清空指派人信息
                        }
                    }
                },error(data){
                    props.button.setButtonsVisible({
                        [pageButton.billSubmit]: true
                    });
                }
            });
        }
        ,
        [pageButton.billSaveSubmit]: async () => {//保存提交
            let props = this.props;
            //提交校验附件是否必须上传
            const is_uploaded = await isUploadedAttachments.call(this, props)
            if(!is_uploaded) return
            let checkResult = props.form.isCheckNow('head') && props.cardTable.checkTableRequired();
            if(checkResult){
                let allData = props.createExtCardData(props.meta.getMeta().code, "head", bodys);
                let filterEmptyData = filterEmptyRows(allData);
                delete3status(filterEmptyData)
                allData = filterEmptyData;
                let multiLang = this.props.MutiInit.getIntl(2011); //this.moduleId
                //无金额的不校验金额字段 noamount=true不需要校验金额
                if(!window.presetVar.noamount) {
                    let vat_amount = props.form.getFormItemsValue('head',"orig_amount").value;
                    if(vat_amount==undefined||vat_amount==null||vat_amount==0||vat_amount=='0.00000000'){
                        toast({content:multiLang && multiLang.get('201102FYYT-0019')/*"金额不能为空!"*/,color:'warning'});
                        return;
                    }
                }

                allData.userjson = window.ntbCheck;
                let billdataForFormula = props.createExtCardData(props.meta.getMeta().code, "head", bodys);
                props.validateToSave( billdataForFormula , () => {
                props.button.setButtonsVisible({
                    [pageButton.billSaveSubmit]: false,
                    [pageButton.pageSave]: false
                });
                // TOP NCCLOUD-91597 校验报销标准取模板时需要使用模板ID chengwbc ADD
                allData.templetid = props.meta.getMeta().pageid;
                // BTM NCCLOUD-91597 校验报销标准取模板时需要使用模板ID
                //如果指派点了确定  由于第一次点击保存提交实际上已经保存成功了，指派后再次提交应该走浏览提交逻辑
                let paramStatus = props.getUrlParam('status');
                if(window.sureAssign){
                    paramStatus = "edit";
                }
                if (this.accessorybillid == undefined || this.accessorybillid == 'undefined') {
                    this.accessorybillid = '';
                }
                requestApi.billSubmit({
                    data: allData,
                    status: paramStatus,
                    assignBillId : window.assignBillId,
                    accessorybillid : this.accessorybillid || window.change_accessorybillid || "",
                    success: (data) => {
                        //设置了指派
                        let multiLang = this.props.MutiInit.getIntl(2011); //this.moduleId
                        if(data.data.workflow && data.data.billid && data.data.bill && (data.data.workflow == 'approveflow'|| data.data.workflow == 'workflow')){
                            this.setState({
                                compositedata:data.data,
                                compositedisplay:true
                            }) ;
                            window.assignBillId = data.data.billid;
                            props.form.setFormStatus(head1, statusVar.browse);
                            props.cardTable.setStatus(body1, statusVar.browse);
                            updataFormData(this.props, head1, data.data.bill.head[head1]);
                            data.data.bill.bodys && updatacardTableData(this.props, body1, data.data.bill.bodys[body1]);
                        } else{
                            this.setState({
                                compositedisplay:false
                            }) ;
                            if(data.data.userjson && JSON.parse(data.data.userjson) && JSON.parse(data.data.userjson).bugetAlarm && JSON.parse(data.data.userjson).bugetAlarm.length>0){
                                promptBox({
                                    color: 'warning',       // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
                                    title: multiLang && multiLang.get('201102JCLF_C-0002'),//"提示信息"
                                    content:  (multiLang && multiLang.get('201102JCLF_C-0003'))+ JSON.parse(data.data.userjson).bugetAlarm + (multiLang && multiLang.get('201102JCLF_C-0004')),
                                    noFooter: false,  // 是否显示底部按钮(确定、取消),默认显示(false),非必输
                                    noCancelBtn: false,    // 是否显示取消按钮,，默认显示(false),非必输
                                    beSureBtnName:  multiLang && multiLang.get('2011-0003'),
                                    cancelBtnName: multiLang && multiLang.get('2011-0002') ,
                                    beSureBtnClick: ()=>{
                                        window.ntbCheck = 'true';
                                        pageButtonClick.call(this)['billSaveSubmit']();
                                    },
                                    cancelBtnClick: () => {
                                        if(props.form.getFormItemsValue(head1, 'pk_mtapp_bill').value){
                                            pageTo.specialLinkTo('/erm/erbudgetmg/erbudgetmg/card/index.html',{scene:props.getUrlParam('scene'),status:statusVar.edit,id:props.form.getFormItemsValue(head1, 'pk_mtapp_bill').value,ts:new Date().getTime()});
                                        }else{
                                            pageTo.specialLinkTo('/erm/erbudgetmg/erbudgetmg/card/index.html',{scene:props.getUrlParam('scene'),status:statusVar.add,ts:new Date().getTime()});
                                        }
                                        routeChange.call(this, this.props)
                                        window.assingUsers = [];    //清空指派人信息
                                        window.sureAssign = false;
                                    } // 取消按钮点击调用函数,非必输
                                })
                            }else if(data.data.userjson && JSON.parse(data.data.userjson) && JSON.parse(data.data.userjson).reimmsg && JSON.parse(data.data.userjson).reimmsg.length>0)
                            {
                                promptBox({
                                    color: 'warning',       // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
                                    title: multiLang && multiLang.get('201102JCLF_C-0002'),
                                    content:JSON.parse(data.data.userjson).reimmsg,
                                    noFooter: false,  // 是否显示底部按钮(确定、取消),默认显示(false),非必输
                                    noCancelBtn: true,    // 是否显示取消按钮,，默认显示(false),非必输
                                    beSureBtnName:multiLang && multiLang.get('2011-0003'),
                                    cancelBtnName: multiLang && multiLang.get('2011-0002') ,
                                    closeByClickBackDrop:false,
                                    beSureBtnClick: ()=>{
                                    //处理按钮状态
                                    dataHandle.call(this, data.data.head[head1],props);
                                    //设置表头数据
                                    updataFormData(this.props, head1, data.data.head[head1]);

                                    data.data.body && updatacardTableData(this.props, body1, data.data.body[body1]);
                                    // BTM 性能优化，变更页面数据更新方法
                                    pageTo.specialLinkTo('/erm/erbudgetmg/erbudgetmg/card/index.html',{scene:props.getUrlParam('scene'),status:statusVar.browse,id:props.form.getFormItemsValue(head1, 'pk_mtapp_bill').value,ts:new Date().getTime()});
                                    routeChange.call(this, this.props)
                                    window.assingUsers = [];    //清空指派人信息
                                    window.sureAssign = false;
                                    },
                                    cancelBtnClick: () => {
                                        pageTo.specialLinkTo('/erm/erbudgetmg/erbudgetmg/card/index.html',{scene:props.getUrlParam('scene'),status:statusVar.browse,id:props.form.getFormItemsValue(head1, 'pk_mtapp_bill').value,ts:new Date().getTime()});
                                        routeChange.call(this, this.props)
                                        window.assingUsers = [];    //清空指派人信息
                                        window.sureAssign = false;
                                    }
                                })
                            }
                            else{
                                //处理按钮状态
                                dataHandle.call(this, data.data.head[head1], props);

                                updatePageDataAfter(props, data.data.head[head1], data.data.bodys)

                                // BTM 性能优化，变更页面数据更新方法
                                pageTo.specialLinkTo('/erm/erbudgetmg/erbudgetmg/card/index.html',{scene:props.getUrlParam('scene'),status:statusVar.browse,id:props.form.getFormItemsValue(head1, 'pk_mtapp_bill').value,ts:new Date().getTime()});
                                routeChange.call(this, this.props)
                                window.assingUsers = [];    //清空指派人信息
                                window.sureAssign = false;
                            }
                        }
                    },error(data){
                        props.button.setButtonsVisible({
                            [pageButton.billSaveSubmit]: true,
                            [pageButton.pageSave]: true
                        });
                    }
                });
              } , body1 , null )
            }
        }
        ,
        [pageButton.billRecall]: () => {//收回
            let props = this.props;
            props.form.setFormStatus(head1, statusVar.browse);
            props.cardTable.setStatus(body1, statusVar.browse);
            let allData = props.createExtCardData(props.meta.getMeta().code, "head", bodys);
            requestApi.billRecall({
                data: allData,
                success: (data) => {
                    //设置表头数据
                    updatePageDataAfter(props, data.data.head[head1], data.data.bodys)
                    // BTM 性能优化，变更页面数据更新方法
                    //处理按钮状态
                    dataHandle.call(this, data.data.head[head1],props);
                }
            });
        },[pageButton.fileManager]: () => {//附件管理
            let props = this.props;
            //let billId = props.getUrlParam('id') || this.state.billId || "";
            let billId = props.getUrlParam('billid') || props.getUrlParam('id') || this.state.billId || window.change_accessorybillid ||"";
            let billtype = props.getUrlParam('tradetype') || "";
            if(billId==null || billId==""){
                let billdata =  props.createExtCardData(props.meta.getMeta().code, "head", bodys);
                if (billdata && billdata.head && billdata.head.head && billdata.head.head.rows[0]) {
                    billId = billdata.head.head.rows[0].values.pk_mtapp_bill.value;
                }
            }
            if ((billId==null || billId=="") && !this.state.showUploader){
                //去后台生成单据主键
                requestApi.generatBillId({
                    data: {billtype: billtype},
                    success:(data)=>{
                        console.log(data);
                        let accessorypkfildname = data["pkfieldName"];
                        billId = data[accessorypkfildname];
                        this.accessorybillid = billId;
                        this.setState({
                            billId: billId,
                            showUploader: !this.state.showUploader
                        });
                    },
                    error:(data)=>{
                        toast({ content: data.message, color: 'danger' });
                    }
                });
            } else {
                this.setState({
                    billId: billId,
                    showUploader: !this.state.showUploader
                });
            }

        },[pageButton.billView]: () => {//联查单据
            let props = this.props;
            let billId = this.state.billId || props.getUrlParam('billid') || props.getUrlParam("id");
            let multiLang = this.props.MutiInit.getIntl(2011);

            props.form.setFormStatus(head1, statusVar.browse);
            props.cardTable.setStatus(body1, statusVar.browse);
            let allData = props.createExtCardData(props.meta.getMeta().code, "head", bodys);
            requestApi.billView({
                data : allData,
                success: (data) => {
                    if(data &&  data.data && data.data.jkdBillModel && data.data.jkdBillModel.rows)
                    {
                        this.setState({
                            linkData: data,
                            showModal: true,
                            billId: billId
                        })
                    }else{
                        toast({ content: multiLang&&multiLang.get('201102SQFY-0029')/**'请注意,您联查的借款、报销单没有数据!'**/, color: 'warning' });
                    }
                }
            })
        },[pageButton.pageClose]: () => {//取消
            let props = this.props;
            let status =  props.getUrlParam('status');
            let billdata =  props.createExtCardData(props.meta.getMeta().code, "head", bodys);
            let billId = billdata.head.head.rows[0].values.pk_mtapp_bill.value || props.getUrlParam('id') || this.state.billId || props.getUrlParam('copyFromBillId') || "";
            if(status ==  statusVar.edit){
                requestApi.query({
                    data: {
                        "openbillid": billId,
                        "pagecode": window.presetVar.pageCode
                    },
                    success: (data) => {
                        props.form.setAllFormValue({[head1]: data.data.head[head1]});
                        //设置表体数据
                        // data.data.bodys && updateBodyData(props, data.data.bodys)
                        props.cardTable.setTableData(window.presetVar.body.body1, data.data.bodys[window.presetVar.body.body1]);
                        //重新处理按钮
                        pageTo.specialLinkTo('/erm/erbudgetmg/erbudgetmg/card/index.html',{scene:props.getUrlParam('scene'),status:statusVar.browse,id:billId,ts:new Date().getTime()});
                        routeChange.call(this, this.props)
                    }
                })

       }else{
               window.onbeforeunload=null;
                window.top.close();
            }

        },
        [pageButton.linkVoucher]:() => {
            let props = this.props;
            let multiLang = this.props.MutiInit.getIntl(2011);
            let paramurl = getRequest1(parent.window.location.hash);
            //如果没取到应用主键再取一下外层,主要适配作业任务打开单据时联查凭证
            if(!paramurl.ar){
                paramurl = getRequest1(parent.parent.window.location.hash);
            }
            if(paramurl.ar){
                let billdata =  props.createExtCardData(props.meta.getMeta().code, "head", bodys);
                if (billdata.head.head.rows.length){
                    linkVoucherApi.link({
                        data  : {
                            props : props,
                            record : {
                                pk_billtype : billdata.head.head.rows[0].values.pk_tradetype.value,
                                pk_group : billdata.head.head.rows[0].values.pk_group.value,
                                pk_org : billdata.head.head.rows[0].values.pk_org.value,
                                relationID : billdata.head.head.rows[0].values.pk_mtapp_bill.value,
                            },
                            appid : paramurl.ar
                        }
                    })
                }else{
                    toast({ content: multiLang&&multiLang.get('201102SQFY-0030')/**'联查凭证失败，缺少应用主键'**/, color: 'danger' });
                }
            }
        },
        [pageButton.linkBudget]:() => {
            let props = this.props;
            let billdata =  props.createExtCardData(props.meta.getMeta().code, "head", bodys);
            if (billdata.head.head.rows.length){
                linkBudgetApi.link({
                    data : {
                        "tradetype": billdata.head.head.rows[0].values.pk_tradetype.value,
                        "openbillid" : billdata.head.head.rows[0].values.pk_mtapp_bill.value
                    },
                    success: (data) => {
                        this.setState({
                            sourceData: data,
                            showLinkBudget: true
                        })
                    }
                })
            }
        },
        [pageButton.billApprove]: () => {
            let props = this.props;
            let billdata = props.createExtCardData(props.meta.getMeta().code, "head", bodys);
            let pk_billtype = billdata.head.head.rows[0].values.pk_tradetype.value;
            let billId = billdata.head.head.rows[0].values.pk_mtapp_bill.value || props.getUrlParam('id') || this.state.billId || "";
            this.setState({
                ShowApproveDetail: true,
                billId: billId,
                billtype: pk_billtype
            });
        },

        [pageButton.linkQueryChangeHistory]: () => {
            const props = this.props
            let billId = this.state.billId || props.getUrlParam('billid') || props.getUrlParam("id");
            ajax({
                url: '/nccloud/erm/erbudgetmg/FysqForChangeHistoryAction.do',
                data: {
                    tradetype: window.presetVar.tradetype,//交易类型
                    openBillId: billId//单据主键ok
                },
                success: result => {
                    if (result.data && result.data.jkdBillModel) {
                        this.setState({
                            linkChangeHisData: result,
                            showLinkQueryChangeHistory: true,
                            billId: billId
                        })
                    } else if (result.data && result.data.sqdList) {
                        result.data.sqdList.forEach((item) => {
                            linkQueryApi.link({
                                data : {
                                    openbillid : item.pk,
                                    tradetype : item.tradetype,
                                    props : this.props
                                }
                            });
                        })
                    } else if (result.data && result.data.tradetype && result.data.pk) {
                        linkQueryApi.link({
                            data : {
                                openbillid : result.data.pk,
                                tradetype : result.data.tradetype,
                                props : this.props
                            }
                        });
                    } else {
                        let multiLang = this.props.MutiInit.getIntl(2011); //this.moduleId
                        toast({ content: multiLang && multiLang.get('201102JCLF_C-0001'), color: 'warning' });
                    }
                }
            });
        },
    }
}

/*
 * @method   if条件下为false   除去NaN、0、-0、false   剩余undefined、null、""
 * @author   add by yangguoqiang @18/03/19
 * @params
 *     condition     {any}
 * @return   {boolean}       返回ture/false
 * @demo     isWrong('')    因为后台返回数据不规范
 */
function isWrongFalse(param) {
    return typeof param === 'undefined' || param === null || param === '' || param === false;
}


/**
 * modify by qiufh@yonyou.com from the platform source
 * 32、移除没有输入内容，所有的空行
 * @param  tableId   meta的id号
 * @param  key       data的键值
 */
function filterEmptyRows(allData, keys) {
    window.presetVar.bodys.forEach(bodyCode => {
        if (allData.bodys[bodyCode].rows && allData.bodys[bodyCode].rows.length > 0) {
            allData.bodys[bodyCode].rows.forEach((item, index) => {
                let values = item.values;
                let tempArr = Object.keys(values).filter(item => item != 'numberindex');
                if (Array.isArray(keys)) {
                    tempArr = tempArr.filter(function (val) {
                        return keys.every(function (key) {
                            return val !== key
                        })
                    })
                }
                // flag 为true 说明每个字段  （要不然不是对象  TODO ? 应该不需要判断 略）   或者 没值
                let flag = tempArr.every(one => (isWrongFalse(values[one].value)))
                flag && (delete allData.bodys[bodyCode].rows[index])
            })
            allData.bodys[bodyCode].rows = allData.bodys[bodyCode].rows.filter(item => !!item)
        }
    })
    return allData;
}

export default pageButtonClick;

// xuzd5 适配到1909
function getRequest1(url) {
    if (!url)
        url = document.location.search;
    let sessionInfo = ""
    if (url.indexOf("page=") != -1) {
        //获取url中页面page参数 1909url中参数仅有page
        var page;
        if (url.indexOf("?") != -1) {
            var str = url.substring(url.indexOf("?") + 1);
            var strs = str.split("&");
            page = strs[0].split("=")[1];
        }

        //根据page获取session storage中原来1903url中的参数
        var msg = getGlobalStorage('sessionStorage', 'NCCAPPURL');
        msg = JSON.parse(msg);
        sessionInfo = msg[page];
    } else if (url.indexOf("?") != -1) {
        sessionInfo = url.substring(url.indexOf("?") + 1);
    } else {
        sessionInfo = url;
    }


    //解析参数
    var theRequest = new Object();
    var strs = sessionInfo.split("&");
    for (var i = 0; i < strs.length; i++) {
        theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
    }
    return theRequest;
}

function updatePageDataAfter(props, headData, bodys) {
    updataFormData(props, head1, headData);
    bodys && updateBodyData(props, bodys)
}
